package cn.tedu._05article_test.controller;

import cn.tedu._05article_test.base.response.JsonResult;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@Slf4j
@Api(tags = "2.文件上传模块")
@RestController
@RequestMapping("/v1/file/")
public class UploadController {
    @ApiOperation("文件上传功能")
    @ApiOperationSupport(order = 10)
    @PostMapping("upload")
    public JsonResult upload(MultipartFile file)throws IOException {
        log.debug("开始处理文件上传");
        //创建文件名
        String filename = file.getOriginalFilename();
        log.debug("原始文件名：" + filename);
        String suffix = filename.substring(filename.lastIndexOf("."));
        log.debug("文件后缀：" + suffix);
        filename = UUID.randomUUID() + suffix;
        log.debug("文件名：" + filename);
        //处理时间格式
        //生成处理时间的格式
        SimpleDateFormat sdf = new SimpleDateFormat("/yyy/MM/dd/");
        String datapath = sdf.format(new Date());
        log.debug("自定义日期格式的路径：" + datapath);
        String staticPath = "e:/files";
        //创建文件
        File dirFile = new File(staticPath + datapath);
        if(!dirFile.exists()){
            dirFile.mkdirs();
        }
        //保存文件到服务器
        String filePath = staticPath + datapath + filename;
        file.transferTo(new File(filePath));
        //返回响应
        return JsonResult.ok(datapath+filename);
    }
}
